//
//  HLSReverseProxyServer.m
//  screen_Test
//
//  Created by 缴天朔 on 2021/9/14.
//

#import "HLSReverseProxyServer.h"

@interface HLSReverseProxyServer(){
    NSString *originURLKey;
}
@property (nonatomic, strong) GCDWebServer *webServer;
@property (nonatomic, strong) NSURLSession *urlSession;
@property (nonatomic, strong) PINCache *cache;
@property (nonatomic, assign) NSUInteger port;
@end

@implementation HLSReverseProxyServer

-(instancetype)initWithGCDWebServer:(GCDWebServer *)webServer URL:(NSURL *)url PINCache:(PINCache *)cache{
    self.webServer = webServer;
    self.url = url;
    self.cache = cache;
    [self addRequestHandler];
    return self;
}

#pragma mark - Start and Stop Server
-(void)start:(NSUInteger)port{
    if (self.webServer.isRunning) {
        return;
    }
    self.port = port;
    _webServer = [[GCDWebServer alloc] init];
    [_webServer startWithPort:9479 bonjourName:nil];
    NSLog(@"The address of webServer is %@",self.webServer.serverURL);
}

-(void)stop{
    if (!self.webServer.isRunning) {
        return;
    }
    self.port = 0;
    [self.webServer stop];
}

#pragma mark - Resource URL
-(NSURL *)reverseProxyURL:(NSURL *)oriUrl{
    NSNumber *port = [[NSNumber alloc] initWithUnsignedInteger:self.port];
    NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithURL:oriUrl resolvingAgainstBaseURL:false];
    urlComponents.scheme = @"http";
    urlComponents.host = @"127.0.0.1";
    urlComponents.port = port;
//    NSURLQueryItem * originUrlQueryItem = [NSURLQueryItem queryItemWithName:originURLKey value:oriUrl.absoluteString];
    
    
    return urlComponents.URL;
}

#pragma mark - Resource Handler
-(void)addRequestHandler{
    [self addPlaylistHandler];
    [self addSegmentHandler];
}

-(void)addPlaylistHandler{
    __weak typeof(self)weakSelf = self;
    [self.webServer addHandlerForMethod:@"GET" pathRegex:@"^/,*\\.m3u8$" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerRequest * _Nonnull request) {
        if (!weakSelf) {
            return  [[GCDWebServerResponse alloc] initWithStatusCode:500];
        }
        NSURL *originUrl = [weakSelf originURL:request];
        if (!originUrl) {
            return [[GCDWebServerResponse alloc] initWithStatusCode:400];
        }
        __block BOOL isE = false;
        NSURLSessionDataTask *task = [weakSelf.urlSession dataTaskWithURL:originUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (!data || !response) {
                isE = true;
            }
            
        }];
        if (isE) {
            return  [[GCDWebServerResponse alloc] initWithStatusCode:500];
        }
        
    }];
}



-(NSURL *)originURL:(GCDWebServerRequest *)request{
    NSString *encodedURLString = [request.query objectForKey:originURLKey];
    NSString *urlString = [encodedURLString stringByRemovingPercentEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    return url;
}

-(NSData *)reverseProxyPlaylistWithData:(NSData *)data forOriginURL:(NSURL *)originURL{
    
}

@end
